const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-session')
const cors = require('koa2-cors');
// const koajwt = require('koa-jwt');


const config = require('./config/default')
const index = require('./routes/index')
const users = require('./routes/users')
const stat = require('./routes/stat')

// error handler
onerror(app)

app.proxy = true

// middlewares
app.keys = ['some secret hurr'];
app.use(session(config.session, app));

// app.use(koajwt({ secret: config.SECRET, passthrough:true, cookie:process.env['token.name'] }).unless({
//   // 登录接口不需要验证
//   path: [/^\/user\//, /^\/user2\/login/]
// }));

app.use(
  cors({
      origin: function(ctx) {
        if (!ctx.header.referer) {
          return ''
        }
        const whiteList = process.env.whitelist.split(','); //可跨域白名单
        let url = ctx.header.referer.substr(0,ctx.header.referer.length - 1);
        if(whiteList.includes(url)){
            return url //注意，这里域名末尾不能带/，否则不成功，所以在之前我把/通过substr干掉了
        }
        // 仅用于测试
        return 'http://localhost:3000' //默认允许本地请求3000端口可跨域
      },
      maxAge: 5, //指定本次预检请求的有效期，单位为秒。
      credentials: true, //是否允许发送Cookie
      allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
      exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
  })
);


app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(stat.routes(), stat.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
